/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore.servlet;

import it.unitn.science.matr155863_148346_145963.bccstore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccstore.items.User;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class LoginSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(LoginSRV.class);
    
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<div id=\"login\">");
        try {
            User user=(User)request.getSession().getAttribute("user");
            if(user==null){
                user=successLogin(request,out);
                if(user==null){
                    showForm(request,out);
                }else{
                    out.println("<h2>"+user.getUsername()+"</h2>");
                    out.println("<a href=\""+request.getContextPath()+"/services/Logout\">Logout</a>");
                }
            }else{
                out.println("<h2>"+user.getUsername()+"</h2>");
                out.println("<a href=\""+request.getContextPath()+"/services/Logout\">Logout</a>");
            }
        }catch(Exception ex){
            log.error(ex);
            RequestDispatcher dispatcher=request.getRequestDispatcher("/contents/public/errorPage.html");
            dispatcher.include(request, response);
        } finally {           
            out.println("</div>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private User successLogin(HttpServletRequest request,PrintWriter out) {
        User user=null;
        if(request.getParameter("username")!=null){
            user=db.authenticate(request.getParameter("username"),request.getParameter("password"));
            if(user==null){
                out.println("<p>Username o password non corretti</p>");
                log.warn("Access with bad val by: "+request.getRemoteAddr());
            }else{
                request.getSession().setAttribute("user", user);
            }
        }
        return user;
    }

    private void showForm(HttpServletRequest request, PrintWriter out) {
                    out.println("<form name=\"login\" method=\"post\" "
                        + "action=\""+request.getContextPath()+"/contents/public/home\" >"
                        + "<label>Username:</label><input type=\"text\" name=\"username\">"
                        + "<label>Password:</label><input type=\"password\" name=\"password\">"
                        + "<input type=\"submit\" name=\"Login\" class=\"button\" value=\"Login\">"
                        + "</form>");
    }
}
